package thread;

public class Main
{

    public static void main(String[] args)
    {
        Account a = new Account("财富", 600);
        new DrawThread("甲", a, 600).start();
        new DepositThread("乙", a, 600).start();
    }

    static class Account
    {
        public String accountName;
        public double balance;
        public boolean hasMoney;

        public Account(String accountName, double balance)
        {
            this.accountName = accountName;
            this.balance = balance;
        }

        public synchronized void draw(String name, double money)
        {
            try
            {
                if(!hasMoney)
                    wait();
                else
                {
                    if(balance >= money)
                    {
                        balance = balance - money;
                        Thread.sleep(2);
                        System.out.println(name + "取走金额：" + money + "元，账户剩余：" + balance + "元");
                        hasMoney = false;
                        notifyAll();
                    }else
                    {
                        System.out.println(name + "欲取走"+money +"元，余额不足");
                    }
                }

            }catch (Exception r){}
        }

        public synchronized void deposit(String name, double dm)
        {
            try
            {
                if(hasMoney)
                    wait();
                else
                {
                    balance += dm;
                    System.out.println(name + "存款：" + dm + "元，账户剩余：" + balance + "元");
                    hasMoney = true;
                    notifyAll();
                }
            }catch(Exception e){}

        }
    }

    static class DrawThread extends Thread
    {

        private Account main;
        private double money;
        private String name;

        public DrawThread(String name, Account main, double money)
        {
            this.name = name;
            this.main = main;
            this.money = money;
        }

        @Override
        public void run()
        {
            for (int i = 0; i < 20; i++)
            {
                main.draw(name, money);
            }
        }
    }

    static class DepositThread extends Thread
    {
        private Account main;
        private double money;
        private String name;

        public DepositThread(String name, Account main, double money)
        {
            this.name = name;
            this.main = main;
            this.money = money;
        }

        @Override
        public void run()
        {
            for (int i = 0; i < 20; i++)
            {
                main.deposit(name, money);
            }
        }
    }
}
